import { _decorator, Component, Node, macro, RigidBody2D, Vec2, Collider2D, Contact2DType, PhysicsSystem2D, director, PhysicsSystem } from 'cc';
const { ccclass, property } = _decorator;

import { AxInput } from './AxInput';
const Input = AxInput.instance;

@ccclass('Player')
export class Player extends Component {
    
    @property
    speed=6;
    @property
    jump_speed = 16;
    
    private can_jump = true;


    onLoad() {
        PhysicsSystem.instance.enable=true;
        PhysicsSystem2D.instance.gravity = new Vec2(0, -600);

        let colliders = this.getComponents(Collider2D);

        for (let collider of colliders) {
            if (collider.tag == 1 || collider.tag == 2) {
                collider?.on(Contact2DType.BEGIN_CONTACT, () => {
                    let gravity = PhysicsSystem2D.instance.gravity;
                    if (Math.sign(gravity.y) > 0 && collider.tag == 1) {
                        return;
                    } else if (Math.sign(gravity.y) < 0 && collider.tag == 2) {
                        return;
                    }
                    this.can_jump = true;
                }, this);
            }
        }
    }

    update() {


        let rigid = this.getComponent(RigidBody2D);
        let linear = rigid!.linearVelocity;

        let gravity = PhysicsSystem2D.instance.gravity;

        if (Input.is_action_pressed(macro.KEY.a)) {
            linear.x = -this.speed;
        } else if (Input.is_action_pressed(macro.KEY.d)) {
            linear.x = this.speed;
        } else {
            linear = new Vec2(0, linear.y);
        }

        //跳跃
        if (Input.is_action_just_pressed(macro.KEY.w) && this.can_jump) {
            linear.y = this.jump_speed * -Math.sign(gravity.y);
            this.can_jump = false;
        }

        //切换重力
        if (Input.is_action_just_pressed(macro.KEY.space)) {
            PhysicsSystem2D.instance.gravity = new Vec2(gravity.x, -gravity.y);
        }
        rigid!.linearVelocity = linear;
    }
}